//
//  QRCoderViewController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/9/23.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "QRCoderViewController.h"
#import "AddDeviceViewController.h"
#import "AddNewCameraController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <ZXingObjC/ZXingObjC.h>
#import "MQTTSessionManager.h"
#import "MQTTCoverTool.h"
#import "XAIGateway.h"
#import "GatewayUtil.h"
#import "UIView+HUD.h"
#import "YSCommon.h"

@interface QRCoderViewController ()
<
AVCaptureMetadataOutputObjectsDelegate,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate
>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ScanBoxHeightCons;
@property (weak, nonatomic) IBOutlet UIImageView *QRCoderScanLine;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraints;
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic, strong)CADisplayLink *displayLink;
@end

@implementation QRCoderViewController

#pragma mark - life 

- (void)dealloc {
    debugLogInfo(@" QRCoderViewController dealloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCamera];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    // Start
    [_session startRunning];
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(scanLineAnimation)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLink = displayLink;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

+ (QRCoderViewController *)createQRCoderViewController {
    UIStoryboard *currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    return  [currentBoard instantiateViewControllerWithIdentifier:@"QRCoderView"];
}
- (IBAction)back {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)photoLibraryClick {
    
    if ([self isGetPhotoPermission]) {
        [self openLocalPhoto];
    }else {
        [self.view yh_showMsgHUD:@"请到 设置->隐私 中开启本程序相册权限"];
    }
}

- (BOOL)isGetPhotoPermission {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if ( author == ALAuthorizationStatusDenied ) {
            return NO;
        }
        return YES;
    }
    PHAuthorizationStatus authorStatus = [PHPhotoLibrary authorizationStatus];
    if ( authorStatus == PHAuthorizationStatusDenied ) {
        return NO;
    }
    return YES;
}

- (void)openLocalPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    ZXCGImageLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:image.CGImage];
    ZXHybridBinarizer *binarizer = [[ZXHybridBinarizer alloc] initWithSource: source];
    ZXBinaryBitmap *bitmap = [[ZXBinaryBitmap alloc] initWithBinarizer:binarizer];
    NSError *error;
    id<ZXReader> reader;
    if (NSClassFromString(@"ZXMultiFormatReader")) {
        reader = [NSClassFromString(@"ZXMultiFormatReader") performSelector:@selector(reader)];
    }
    ZXDecodeHints *_hints = [ZXDecodeHints hints];
    ZXResult *result = [reader decode:bitmap hints:_hints error:&error];
    if (result == nil) {
        debugLogInfo(@"无QRCode");
        return;
    }
    debugLogInfo(@"QRCode = %d，%@",result.barcodeFormat,result.text);
    if (self.enterVcType == EnterScanControllerTypeAddGateWay) {
        NSArray * strArray = [result.text componentsSeparatedByString:@","];
        if (strArray.count != 2) {
            [self.view yh_showMsgHUD:@"无效的二维码"];
            return;
        }
        NSString *strApsn = strArray[0];
        XAITYPEAPSN apsn = (XAITYPEAPSN) [MQTTCoverTool decimalWithHexString:strApsn];
        if (0 == apsn) {
            [self.view yh_showMsgHUD:@"无效的二维码"];
            return;
        }
        kMQTTSessionManager.tmpApsn = apsn;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSError*error =  [kMQTTSessionManager.xai bindGatewayWithApsn:apsn gatewayLuid:0x01 message:@"iOS"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error.code == 0) {
                    [self.view yh_showMsgHUD:@"告知管理员成功，需等到管理员同意"];
                } else {
                    [self.view yh_showMsgHUD:@"绑定失败"];
                    debugLogInfo(@"error = %@",error.localizedDescription);
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
        });
    }
}

- (IBAction)CancelScan {
    [self.displayLink invalidate];
    self.displayLink = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setInfo:(LCOpenSDK_Api*)hc token:(NSString*)token  phone:(NSString *)phone  devView:(id)view {
    if (token.length == 0) {
        debugLogInfo(@"没有token");
        return;
    }
    if (phone.length == 0) {
        debugLogInfo(@"没有phone");
        return;
    }
    self.enterVcType = EnterScanControllerTypeAddNewCamera;
    self.m_hc = hc;
    self.m_strAccessToken = token;
    self.m_strPhone = phone;
}
-(void) setInfo:(LCOpenSDK_Api*)hc token:(NSString*)token devView:(id)view {
    self.enterVcType = EnterScanControllerTypeAddNewCamera;
    self.m_hc = hc;
    self.m_strAccessToken = token;
    self.m_strPhone = nil;
}

- (void)setupCamera {
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input]) {
        [_session addInput:self.input];
    }
    if ([_session canAddOutput:self.output]) {
        [_session addOutput:self.output];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *stringValue;
    if ([metadataObjects count] >0) {
        //停止扫描
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        debugLogInfo(@"stringValue = %@", stringValue);
        [self.displayLink invalidate];
        self.displayLink = nil;
        if (stringValue.length == 0) {
            [self.view yh_showMsgHUD:@"无效的二维码"];
            return;
        }
        switch (self.enterVcType) {
            case EnterScanControllerTypeAddNewCamera:
            {
                AddNewCameraController *addCameraVc = [[AddNewCameraController alloc]init];
                NSRange range = [stringValue rangeOfString:@"SN:"];
                NSRange range2 = [stringValue rangeOfString:@","];
                NSRange range3 =  NSMakeRange(range.location+ range.length, range2.location - range.location -range.length);
                NSString *str = [stringValue substringWithRange:range3];
                [addCameraVc setInfo:self.m_hc token:self.m_strAccessToken serial:str phone:self.m_strPhone devView:self];
                [self.navigationController pushViewController:addCameraVc animated:YES];
            }
                break;
            case EnterScanControllerTypeAddGateWay:
            {
                NSArray * strArray = [stringValue componentsSeparatedByString:@","];
                NSString *strApsn = strArray[0];
                XAITYPEAPSN apsn = (XAITYPEAPSN) [MQTTCoverTool decimalWithHexString:strApsn];
                if (0 == apsn) {
                    [self.view yh_showMsgHUD:@"二维码绑定网关失败"];
                    [self.navigationController popViewControllerAnimated:YES];
                    return;
                }
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSError*error =  [kMQTTSessionManager.xai bindGatewayWithApsn:apsn gatewayLuid:0x01 message:@"iOS"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                        if (error.code == 0) {
                            [UIApplication.sharedApplication.keyWindow yh_showMsgHUD:@"告知管理员成功，需等到管理员同意"];
                        } else {
                            [UIApplication.sharedApplication.keyWindow yh_showMsgHUD:@"绑定失败"];
                            debugLogInfo(@"error = %@",error.localizedDescription);
                        }
                    });
                });
            }
                break;
            case EnterScanControllerTypeAddFriend:
            {
                NSArray * strArray = [stringValue componentsSeparatedByString:@","];
                if (strArray.count != 3) {
                    [self.view yh_showMsgHUD:@"无效的二维码"];
                }
                NSString *strApsn = strArray[1];
                XAITYPEAPSN apsn = (XAITYPEAPSN) [MQTTCoverTool decimalWithHexString:strApsn];
                NSString *strLuid = strArray[2];
                XAITYPELUID luid = [MQTTCoverTool decimalWithHexString:strLuid];
                XAITLV* apsnTLV = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
                XAITLV* luidTLV = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
                NSString* extrctInfo = @"是否允许?";
                NSData* infoData = [extrctInfo dataUsingEncoding:NSUTF8StringEncoding];
                XAITLV* textTLV = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void *) infoData.bytes length:infoData.length];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSError* error = [kMQTTSessionManager.xai sendCMD:0x01 toApsn:kZTCloudGatewayApsn toLuid:kGATEWAYLUID datas:@[apsnTLV,luidTLV, textTLV]];
                    debugLogInfo(@"%@",error.localizedDescription);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                        [UIApplication.sharedApplication.keyWindow yh_showMsgHUD:@"已发送添加好友请求，需等待同意。"];
                    });
                });
            }
            default:
                break;
        }
    } else {
        debugLogInfo(@"无扫描信息");
        return;
    }
}

- (void)scanLineAnimation {
    self.bottomConstraints.constant -= 1;
    if (self.bottomConstraints.constant <= -self.ScanBoxHeightCons.constant) {
        self.bottomConstraints.constant = 0;
    }
}

@end
